package testjeu;

import java.io.File;
import java.io.FilenameFilter;
import java.util.logging.Level;
import java.util.logging.Logger;

import mdes.slick.sui.Button;
import mdes.slick.sui.Display;
import mdes.slick.sui.DraggableContainer;
import mdes.slick.sui.Label;
import mdes.slick.sui.Sui;
import mdes.slick.sui.TextField;
import mdes.slick.sui.Window;
import mdes.slick.sui.event.ActionEvent;
import mdes.slick.sui.event.ActionListener;
import mdes.slick.sui.layout.RowLayout;
import mdes.slick.sui.theme.SteelBlueTheme;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;

/**
 * # 1er state # Affiche le menu principal du jeu
 * 
 * @author YoTsumi
 */
public class Menu extends BasicGameState implements Constantes {

	
        private Image Splash, Menu1[], Menu2[], Menu3[], Instructions;
        private int id1, id2, id3;
        private boolean AfficherInstructions=false;
        
        private Window  win;
        private Display display;
        private TextField  txt;
        private String txtDécodé;
        
        
        public static String map;
        public static boolean mapValide;
        private StateBasedGame gamee;
        
        private int nb_maps;
        
        /** Gestionnaire de messages */
        public Messages messages;          
                
        /**
         * Retourne l'ID du state en cours
         * @return Id du state
         */
        public int getID()
        {
            return ID_menu;
        } 
        
        
        /**
	 * @see org.newdawn.slick.state.BasicGameState#init(org.newdawn.slick.GameContainer, org.newdawn.slick.state.StateBasedGame)
	 */
	public void init(GameContainer container, final StateBasedGame game) throws SlickException {
		this.gamee = game;
        messages=new Messages(0);
	    
	    Menu1=new Image[2]; Menu2=new Image[2]; Menu3=new Image[2];
	    
	    Splash=new Image("res/splash.jpg");
	    Instructions=new Image("res/explications.png");
	    Menu1[0]=new Image("res/menu_1.png"); Menu1[1]=new Image("res/menu_1h.png");
	    Menu2[0]=new Image("res/menu_2.png"); Menu2[1]=new Image("res/menu_2h.png");
	    Menu3[0]=new Image("res/menu_3.png"); Menu3[1]=new Image("res/menu_3h.png");
	    
	    id1=id2=id3=0;
	    
	    // On compte le nbre de maps
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.contains(".tmx");
            }
        };

	   File Dossier = new File(MAP_DIR);
	   nb_maps=Dossier.listFiles(filter).length;
	    
	    
	    
	    // Création de la petite fenetre charger map
	    display = new Display(container);
	    
	    SteelBlueTheme theme = new SteelBlueTheme();
	    Sui.setTheme(theme);
	    Sui.updateComponentTreeTheme(display); 
	    
	    win = new Window();
	    win.setAlwaysOnTop(true);
	    win.setSize(155,100);
	    win.setOpaque(true);
	    win.setLocation(640, 250);
	    win.setBackground(new Color(0,0,0,180));
	    win.addMouseListener(DraggableContainer.createDragListener(win));
	    win.setVisible(false);
	    
	    RowLayout layout = new RowLayout(false, RowLayout.CENTER, RowLayout.CENTER);
	    win.setLayout(layout);
	
	        // Label
	        Label expl = new Label("Code secret ?");
	        expl.setForeground(Color.white);
	        expl.pack();
	        win.add(expl);
	
	        // Input
	        txt=new TextField(4);
	        txt.setHeight(20);
	        txt.setToolTipText("Code secret de la map");
	        txt.setBackground(Color.darkGray);
	        txt.setMaxChars(4);
	        win.add(txt);
	
	        // Bouton
	        Button btn = new Button("Go !");
	        btn.pack(); 
	        win.add(btn);
	        
	        btn.addActionListener(new ActionListener() {
	
	            public void actionPerformed(ActionEvent e) {
	                
	                if ( txt.getText().length()==4) {
	                
	                   txtDécodé = Crypto.decrypt(txt.getText(), 3);
	                   
	                       FilenameFilter filter = new FilenameFilter() {
	                            public boolean accept(File dir, String name) {
	                                return name.contains(txtDécodé);
	                            }
	                        };
	
	                   File Dossier = new File(MAP_DIR);
	                   File[] Liste = Dossier.listFiles(filter);
	                   if (Liste.length==1) {
	                        try {
	                            messages.ajouter("Chargement de la map en cours", 300, 2);
	                        } catch (SlickException ex) {
	                            Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
	                        }
	                        
	                        Menu.mapValide=true;
	                        Menu.map=Liste[0].getName().substring(0, 7);
	                        gamee.enterState(ID_jeu, new FadeOutTransition(), new FadeInTransition());
	                   } else {
	                       
	                       try {
	                           messages.ajouter("Code incorrect !", 300, 2);
	                           } catch (SlickException ex) {
	                               Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
	                        }
	                   }
	                } else {
	                       try {
	                           messages.ajouter("Un code secret comporte 4 lettres !", 300, 2);
	                           } catch (SlickException ex) {
	                               Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
	                        }                                
	                }
	                    
	            }
	        });
	
	     
	     display.add(win);


	}

		/**
		 * @see org.newdawn.slick.state.BasicGameState#render(org.newdawn.slick.GameContainer, org.newdawn.slick.state.StateBasedGame, org.newdawn.slick.Graphics)
		 */
		public void render(GameContainer container, StateBasedGame game, Graphics g) {
	            Splash.draw(0,0);
	            Menu1[id1].draw(624,391);
	            Menu2[id2].draw(624,444);
	            Menu3[id3].draw(624,497);
	            if (AfficherInstructions) Instructions.draw(49,49);
	                    
	            display.render(container, g);
	            messages.dessiner(g);
	            
	            g.drawString(nb_maps+" maps", 115, 627);
		}

		/**
		 * @see org.newdawn.slick.state.BasicGameState#update(org.newdawn.slick.GameContainer, org.newdawn.slick.state.StateBasedGame, int)
		 */
		public void update(GameContainer container, StateBasedGame game, int delta) {
	           display.update(container, delta);
	           messages.update(delta);
	
		}

 
        /**
         * Lorsque la souris est déplacé : Survol des menus
         * 
         * @param oldx  Ancienne coordonnée x
         * @param oldy  Ancienne coordonnée y
         * @param newx  Nouvelle coordonnée x
         * @param newy  Nouvelle coordonnée y
         */
        @Override
        public void mouseMoved(int oldx, int oldy, int newx, int newy) {
            if (newx>=624+10 && newx<=624+230-10) {
                if      (newy>=391+10 && newy<=391+53-10) { id1=1; id2=id3=0; }
                else if (newy>=444+10 && newy<=444+53-10) { id2=1; id1=id3=0; }
                else if (newy>=497+10 && newy<=497+53-10) { id3=1; id1=id2=0; }
                else                                      { id1=id2=id3=0; }
            }   else                                      { id1=id2=id3=0; }
        }

        
                
        /**
         * Lorsque qu'un bouton de la souris est relaché : Lancement d'un menu
         * 
         * @param button
         * @param x
         * @param y
         */
        @Override
        public void mouseReleased(int button, int x, int y) {
            if (x>=624+10 && x<=624+230-10) {
                if      (y>=391+10 && y<=391+53-10) gamee.enterState(ID_jeu, new FadeOutTransition(), new FadeInTransition());
                else if (y>=444+10 && y<=444+53-10) { win.setVisible(!win.isVisible()); txt.grabFocus(); }
                else if (y>=497+10 && y<=497+53-10) AfficherInstructions=!AfficherInstructions;
            }
            if (x>=580 && x<=590 && y>=65 && y<=65) AfficherInstructions=false;
        }
}
